
function unixtimeToDate(ut) {
    var TZ = 9;
    var tD = new Date( ut * 1000 );
    tD.setTime( tD.getTime() + (60*60*1000 * TZ) );
    return tD;
}

var SERVER = "/"; /* root */
function createData(data) {
    var user = data.user_name;
    var text = data.text;
    var imgfile = data.image_src;
    var file = SERVER + imgfile;
    var info = unixtimeToDate(data.date).toLocaleString();
    var box = $("<div class=\"row message\"></div>");
    var sp1 = $("<div class=\"span1\"></div>");
    sp1.append($("<img>").attr("src", file).attr("width",48).attr("height",48)).addClass("icon");
    var sp6 = $("<div class=\"span6\"></div>");
    sp6.append($("<p class=\"username\">"+user+"</p>"));
    sp6.append($("<p class=\"tweetmsg\">"+text+"</p>"));
    sp6.append($("<p class=\"tweetinfo\">"+info+"</p>"));
    box.append(sp1);
    box.append(sp6);
    return box;
}

function showErrorDialog(xhr, status, err) {
    var message = "<b>Something wrong with minikonoha!!</b> Please send message.";
    if (status == "timeout") {
        message = "<b>Error occcurred </b>while receiving data";
    }
    $("#pop").attr({
        "title": "Error!!! : " + status + " " + err,
        "data-content": message});
    $("#pop").popover({html:true}).popover("show");
    $("div#slideBox").show();
    $('#status').val("Error!!! : " + err);
};

$(document).ready(function() {
        var URL = 'cgi-bin/twitter/timeline.json';
        $.ajaxSetup({timeout: 5000, error: showErrorDialog, contentType:"application/x-www-form-urlencoded; charset=utf-8", });
        function resultsHandler (data) {
            if (data == null) {
                showErrorDialog();
                return;
            }
	    var div = $("div#msgbox");
            for(var i =0;i<data.length;i++) {
		div.append(createData(data[i]));
            }
        };
        function errorHandler (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus, errorThrown, this);
        };
        $.getJSON(SERVER+URL, resultsHandler);
        $("textarea").keyup(function(){
                var counter = 140 - $(this).val().length;
                var c = $("div.count");
                var color = (counter <= 30) ? "red" : "#666";
                c.text(counter);
                c.css("color", color);
                });
        $('textarea').focus(function() {
                $("div#slideBox").show();
                });
        $(".alert-message").alert('close');
	$("#submit").click(function(){
            $.post( SERVER+'cgi-bin/twitter/tweet.json', { 'text': $("#status").val(), "username" : "imasahiro"},
                function(data){
	    	     var topMessage = $("div.span8:last").children("div#msgbox > div:first");
	             data.text = decodeURI(data.text);
		     createData(data).insertBefore(topMessage);
	        }
            );
        }
    );
	$("#upper-search-form").keyup(function(){
		$("#upper-search-form").val($("#upper-search-form").val().replace("\n", "", "g"));
		$.getJSON( SERVER+'cgi-bin/twitter/search.json?text=' + $("#upper-search-form").val(),
			function(data){
			$("div#msgbox > *").remove();
			var div = $("div#msgbox");
				for(var i =0;i<data.length;i++) {
					div.append(createData(data[i]));
				}
			}		
		)
	});

	
$("a.contact").click(function(){showErrorDialog("", "", "");})
});
